import Taro, { Component, Config } from '@tarojs/taro'
import { Button, Image, ScrollView, Text, View } from '@tarojs/components'
import classNames from 'classnames'
// import lodash from "@/utils/lodash"
import { pxTransform, getElementPosition } from "@/utils/utils"
import moment from "@/assets/js/moment.min"
import { AUTH_TOKEN, SHARE_ID, USER_INFO } from "@/config/storage"
import { SHARE_TYPE } from "@/config/types"
import { getPage, getCount } from "@/api/productApi"
import { getCustomPage } from "@/api/pageApi"
import { shareInfoById } from "@/api/wximagesApi"
import { getAppConfig, goodsScore, TotalScore, getSharePath, getActivityTimeStorage, setActivityTimeStorage, getBrand, getRandomPage, getRandomPageNumber } from '@/utils/storage'
import {
  toAnyPage,
  toGoodsPage,
  toIntegralCheckinPage,
  toSearchPage,
  toOrderListPage,
  toServiceComplaint,
  toComplaint
} from "@/utils/page_router"
import {
  APP_NAME,
  CUSTOM_HOME_PAGE,
  TAB_BAR_HEIGHT,
  APP_SIGN_TAB,
  APP_SIGN_BTN,
  INDEX_APP_CONFIG,
  TAB_BAR_CONFIG
} from '@/config/config'
import { TabBar, Loading, Version, LoadMore, BuyRecord, CustomerService, ExchangeCountdown, HomePrompt } from '@/components/index'
import ActivityGoods from "@/components/activity/goods/index"
// import ActivityCoupon from "@/components/activity/coupon/index"
import NewsOne from "@/components/custom-layout/news-one"
import NavGroupTwo from "@/components/custom-layout/nav-group-two"
import CarouselTwo from "@/components/custom-layout/carousel-two"
import GoodsOne from "@/components/custom-layout/goods-one"
import GoodsTwo from "@/components/custom-layout/goods-two"
import GoodsThree from "@/components/custom-layout/goods-three"
import GoodsFour from "@/components/custom-layout/goods-four"
import GoodsFive from "@/components/custom-layout/goods-five"
import GoodsSix from "@/components/custom-layout/goods-six"
import GoodsSeven from "@/components/custom-layout/goods-seven"
import GoodsEight from "@/components/custom-layout/goods-eight"
import GoodsNine from "@/components/custom-layout/goods-nine"
import GoodsTen from "@/components/custom-layout/goods-ten"
import GridImg from "@/components/custom-layout/grid-img"
import BlankSpace from "@/components/custom-layout/blank-space"
import AuxiliaryLine from "@/components/custom-layout/auxiliary-line"
import homeScoreBg from "@/assets/images/home-score-bg.png"
import GoodsCategories from "@/components/custom-layout/goods-categories"
import ActivityTheme from "@/components/custom-layout/activity-theme"
import Promotion from "@/components/custom-layout/promotion"
import ScrollTop from "@/components/scroll-top"
import './index.scss'
import lodash from '@/utils/lodash'
import { getScoreConfig, getSignScore, addSignScore } from "@/api/userApi";
import { getCommonSonConfig } from "@/api/systemApi";
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"

const defTabKey = 'recommend'
let CAROUSEL_HEIGHT = 0
const TAB_NAV_HEIGHT = 72
// const { capsule } = APP_SYSTEM_INFO
export default class Index extends Component {
  state: any
  navBar: any
  tabNav: any
  pageConfig: any
  activityInfo: any
  config: Config = {
    navigationStyle: 'custom',
    backgroundTextStyle: "dark",
  }

  constructor() {
    super(...arguments)
    const end = moment().endOf('day').valueOf()
    const cur = Number(new Date())
    const time = Math.floor((end - cur) / 1000)
    this.state = {
      tabKey: defTabKey,
      loading: true,
      customList: [],
      page: 1,
      limit: 10,
      seconds: time,
      goodsList: [],
      signList: [],
      dataList: [],
      signScore: 0,
      scoreInfo: {},
      loadStatus: 'loading',
      showActivity: false,
      totalScore: TotalScore(),
      homeGuide: [],
      showRule: false,
      zhiding: false,
      duihuanbi: true,
    }
    this.pageConfig = {}
  }

  componentDidMount() {
    this.getShareInfo()
    this.getIndexData()
    getCommonSonConfig(INDEX_APP_CONFIG, 'homeGuide').then(({ data }) => {
      if (data && data.length > 0) {
        const { items } = data.homeGuide
        this.setState({
          homeGuide: items
        })
      }
    })
  }

  componentDidShow() {
    this.getScore()
  }

  //  上拉加载
  onReachBottom() {
    this.getGoods()
  }

  //  获取积分
  async getScore() {
    const config = await getScoreConfig().then(({ data }) => data)

    await getSignScore().then(({ data }) => {

      const current = moment().subtract(data.currencyDay + (data.isSign ? -1 : 0), 'day')
      const list = config.map(item => {
        const time = current.format('MM.DD')
        current.add(1, 'day')
        return { ...item, time }
      })

      this.setState({
        signList: list,
        scoreInfo: data,
        signScore: list[data.currencyDay]['number']
      })

      setTimeout(() => {
        this.setState({
          loading: false
        })
      }, 800)
    })
  }

  //  分享小程序
  onShareAppMessage() {
    return { title: APP_NAME, path: getSharePath() }
  }

  //  获取分享信息
  getShareInfo() {
    const { params: { scene } }: any = this.$router
    if (scene) {
      Taro.setStorageSync(SHARE_ID, scene)
      shareInfoById(scene).then(({ data }) => {
        const arr = [
          SHARE_TYPE.GOODS_INFO,
          SHARE_TYPE.NORMAL_GOODS,
          SHARE_TYPE.SCORE_GOODS,
          SHARE_TYPE.SECKILL_GOODS,
          SHARE_TYPE.PINK_GOODS,
          SHARE_TYPE.REAL_GOODS,
          SHARE_TYPE.VIRTUAL_GOODS,
        ]
        if (arr.indexOf(data.keyType) >= 0) {
          toGoodsPage({ id: data.keyId, type: data.keyType, saleStrategy: data.keyType }, true)
        }
      })
    }
  }

  onPageScroll(res: any) {
    if (res.scrollTop > 300) {
      this.setState({
        zhiding: true,
      })
    } else {
      this.setState({
        zhiding: false,
      })
    }
    if (res.scrollTop) {
      this.setState({
        duihuanbi: false,
      })
    } else {
      this.setState({
        duihuanbi: true,
      })
    }
  }

  //  获取首页数据
  getIndexData() {
    getCustomPage(CUSTOM_HOME_PAGE).then(({ data, timestamp }) => {
      const list = (data.content || []).map(item => {
        switch (item.key) {
          case 'navGroup':
            const { list = [], colNumber = 5, rowNumber = 2 } = item
            //  乘积
            const product = colNumber * rowNumber
            const num = Math.ceil(list.length / product)
            const arr: any = []
            for (let i = 0; i < num; i++) {
              arr.push([])
            }
            for (let i = 0; i < list.length; i++) {
              arr[Math.floor(i / product)].push(list[i])
            }

            item.list = arr
            break
          case 'carousel':
            CAROUSEL_HEIGHT = item.height
            break
          case 'navBar':
            this.navBar = item
            break
          case 'tabNav':
            item.head = item.head.split('|')
            item.list.map(item => {
              item.name = item.name.split('|')
            })
            this.tabNav = item
            break
          case 'pageConfig':
            this.pageConfig = item
            break
          case 'activityGoods':
            this.activityInfo = item
            break
        }
        return item
      })
      this.setState({
        customList: list
      }, () => {
        this.setState({
          loading: false
        })
        setTimeout(() => {
          Taro.stopPullDownRefresh()
        }, 1500)
      })

      this.activityInfo && setTimeout(() => {
        this.showActivity(timestamp, this.activityInfo)
      }, 3000)
    })
  }

  //  显示活动
  showActivity(time: number, goods: any) {
    const item = getActivityTimeStorage(goods.id)
    if (!item || item && moment(time).isAfter(item['time'])) {
      setActivityTimeStorage(goods.id, {
        id: goods.id,
        type: 'goods',
        time: time + 86400000
      })
      this.setState({
        showActivity: true,
      })
    }
  }

  //  关闭活动
  closeActivity() {
    this.setState({
      showActivity: false,
    })
  }

  //  分页获取商品
  getGoods() {
    const { page, limit, tabKey, goodsList, loadStatus }: any = this.state
    const query = {}
    if (loadStatus === 'noMore') {
      return
    }

    if (tabKey !== defTabKey) {
      query['categoryId'] = tabKey
    }

    const config = getAppConfig('productRandom')

    if (config === '1') {
      getPage({ page: getRandomPageNumber(), limit, ...query }).then(res => {
        const pageArr = getRandomPage()
        const { list, totalCount } = res.data

        this.setState({
          page: page,
          goodsList: !goodsList.length ? list : goodsList.concat(list),
          loadStatus: !pageArr.length ? 'noMore' : 'loading'
        }, () => {
          Taro.stopPullDownRefresh()
        })
      })
    } else {
      getPage({ page, limit, ...query }).then(res => {
        const { list, totalCount } = res.data
        this.setState({
          page: page + 1,
          goodsList: page === 1 ? list : goodsList.concat(list),
          loadStatus: (page * limit >= totalCount) ? 'noMore' : 'loading',
        }, () => {
          Taro.stopPullDownRefresh()
        })
      })
    }


    // getPage({ page, limit, ...query }).then(res => {
    //   const { list, totalCount } = res.data
    //   this.setState({
    //     page: page + 1,
    //     goodsList: page === 1 ? list : goodsList.concat(list),
    //     loadStatus: (page * limit >= totalCount) ? 'noMore' : 'loading',
    //   }, () => {
    //     Taro.stopPullDownRefresh()
    //   })
    // })
  }

  //  切换tab
  onSwitchTab(key) {
    getCount({ 'categoryId': key }).then(() => {
      this.setState({
        page: 1,
        tabKey: key,
        goodsList: [],
        loadStatus: 'loading'
      }, () => {
        this.getGoods()
        const { tabKey } = this.state
        const scrollY = tabKey === 'recommend' ? 70 : 10
        const { y } = getElementPosition(document.getElementById('home-tab-nav'))
        Taro.pageScrollTo({
          scrollTop: y - scrollY,
          duration: 0
        })
      })
    })




    // this.setState({
    //   page: 1,
    //   tabKey: key,
    //   goodsList: [],
    //   loadStatus: 'loading'
    // }, () => {
    //   this.getGoods()
    // })
  }

  // 签到
  homeSign() {
    Taro.showLoading({ mask: true, title: '加载中...' })
    addSignScore().then(() => {
      Taro.hideLoading()
      Taro.showToast({ title: '签到成功' })
      this.getScore()
    })
  }

  //打开兑换币规则
  toExchangeRule(value) {
    this.setState({
      showRule: value
    })
  }

  showDuihuanbi() {
    this.setState({
      duihuanbi: true
    })
  }

  render() {
    const { navBar, tabNav, pageConfig, activityInfo } = this
    const { customList, homeGuide, tabKey, loading, goodsList, loadStatus, seconds, showActivity, signList, signScore, scoreInfo, totalScore, showRule, zhiding, duihuanbi } = this.state
    {/*// @ts-ignore*/ }
    return (<View className='index custom-page' style={{ '--page-bg-img': `url(${pageConfig.bgImg})` }}>
      {loading && <Loading isCover />}
      <ScrollTop ref="ScrollTop" zhiding={zhiding} duihuanbi={duihuanbi} showDuihuanbi={this.showDuihuanbi.bind(this)} />
      <View className='integral-box'>
        <View className='integral-info f-g-5 f-d-c'>
          <div className='home-score-bg'>
            <Image src={homeScoreBg} />
          </div>
          <View className='integral-title t-a-c'>
            我的{getBrand()}
            <View className='integral-number bnn-number m-t-20'>{scoreInfo.totalScore || totalScore}</View>
          </View>
          {/*<View className='integral-number bnn-number'></View>*/}
          {/*<Button className='checkin-btn xf-btn xf-btn-round xf-btn-primary' onClick={() => toIntegralCheckinPage()}>立即签到 + {signScore}</Button>*/}
          {APP_SIGN_BTN &&
            <Button className='checkin-btn xf-btn xf-btn-round xf-btn-primary t-o-e' onClick={this.homeSign.bind(this)}>立即签到
              + {signScore}</Button>}
        </View>

        <View className='menu-list'>
          {homeGuide.map(item => {
            return (<View className='menu-item' onClick={() => toAnyPage(item.url)}>{item.name}</View>)
          })}
          <View className='menu-item' onClick={() => toOrderListPage()}>查询订单</View>
          {/*<View className='menu-item' onClick={() => toIntegralCheckinPage()}>我的{getBrand()}</View>*/}
          <View className='menu-item' onClick={() => toServiceComplaint()}>联系客服</View>
          <View className='menu-item' onClick={this.toExchangeRule.bind(this, true)}>兑换币规则</View>
          {/*<View className='menu-item' onClick={() => toAnyPage(getAppConfig('integralRule'))}>{getBrand()}规则</View>*/}
          {/*<View className='menu-item' onClick={() => toComplaint()}>立即投诉</View>*/}
        </View>

        <View className='integral-prompt f-g-5'>{getBrand()}可兑换商品，二天后过期清零，请尽快使用</View>
      </View>

      {APP_SIGN_TAB && <View className='sign-wrap'>
        <View className='sign-left f-g-5 f-d-c'>
          <View className='sign-title'>已签到</View>
          <View className='sign-day bnn-number'>
            <Text className='sign-day-num'>{scoreInfo.currencyDay}</Text>天
          </View>
        </View>
        <View className='sign-right'>
          <View className='sign-list'>
            {
              signList.map((item, key) => {
                return (
                  <View key={key} className='sign-item bnn-number'>
                    <View className='sign-name'>{item.time}</View>
                    <View className='sign-status'>
                      {
                        key < scoreInfo.currencyDay ? (
                          <View className='sign-circle sign-active bnn-icon'>&#xe645;</View>
                        ) : (
                          <View className='sign-circle' />
                        )
                      }
                    </View>
                    <View className='sign-integral'>+{item.number}</View>
                  </View>
                )
              })
            }
            <View className='sign-line' />
          </View>
        </View>
      </View>}

      {/*<View style='margin-top: -20px'><ExchangeCountdown seconds={seconds}/></View>*/}



      {/*<View/>*/}
      {pageConfig.showTabNav && tabNav && <View className='tab-nav m-b-10'>
        <View className={classNames('tab-nav__left tab-nav__cty-item', { ['tab-nav__cty-active']: tabKey === defTabKey })} onClick={this.onSwitchTab.bind(this, defTabKey)}>
          {/*<View className='tab-nav__cty-text'>*/}
          {/*  <View>{ lodash.head(tabNav.head) }</View>*/}
          {/*  <View>{ lodash.last(tabNav.head) }</View>*/}
          {/*</View>*/}
          <View className='tab-nav__cty-text'>
            <View className='cty-text-head'>{lodash.head(tabNav.head)}</View>
            <View className='cty-text-last'>{lodash.last(tabNav.head)}</View>
          </View>
        </View>
        {/*// @ts-ignore*/}
        {/* <ScrollView scrollX enhanced showScrollbar={false} className='tab-nav__cty-scroll'> */}
        {tabNav.list.map(cty => {
          return (<View key={cty.id} className={classNames('tab-nav__left tab-nav__cty-item', { ['tab-nav__cty-active']: tabKey === cty.id })} onClick={this.onSwitchTab.bind(this, cty.id)}>
            <View className='tab-nav__cty-text'>
              <View className='cty-text-head'>{lodash.head(cty.name)}</View>
              <View className='cty-text-last'>{lodash.last(cty.name)}</View>
            </View>
          </View>)
        })}
        {/* </ScrollView> */}
        {/*<View className='tab-nav__right' onClick={() => toSearchPage()}>全部</View>*/}
      </View>
      }
      <View id='home-tab-nav' className='m-t-30'><ExchangeCountdown seconds={seconds} /></View>

      {/*<ExchangeCountdown id='home-tab-nav' seconds={seconds}/>*/}

      <View className='index-custom' style={{ display: tabKey === defTabKey ? 'block' : 'none' }}>
        <View className='index-custom__bg' style={{ paddingBottom: `${pxTransform(CAROUSEL_HEIGHT)}` }} />
        {customList.map((item, k) => {
          const { marginTop = 0, pageMargin = 0 } = item
          return (<View key={k} className='custom-item'>
            {/*{item.key === 'carousel' ? <CarouselTwo { ...item }/> : null}*/}
            {
              {
                'carousel': <CarouselTwo {...item} />,         // 轮播图
                'navGroup': <NavGroupTwo {...item} />,         // 导航组
                'newPeopleExclusive': <GoodsEight {...item} />,// 新人专享
                'fightGroups': <GoodsNine {...item} />,        // 拼团商品
                'newsService': <NewsOne {...item} />,          // 新闻播报
                'gridImg': <GridImg {...item} />,              // 栅格图片

                //  工具组件
                'blankSpace': <BlankSpace {...item} />,        // 新闻播报
                'auxiliaryLine': <AuxiliaryLine {...item} />,  // 栅格图片
                // 'goodsCategories':  <GoodsCategories { ...item } scroll={scroll} addNode={[ this.navId ]} />,  // 商品分类
                'activityTheme': <ActivityTheme {...item} />,  // 活动专区
                'promotion': <Promotion {...item} />,  // 营销板块
              }[item.key]
            }

            {/* 商品列表模板1 */}
            {item.key === 'seckill' && <View className='goods-wrap goods-wrap__one' style={{ marginTop: `${pxTransform(marginTop)}` }}>
              {item.title && <View className='goods-wrap__head d-f a-i-b j-c-b' style={{ padding: `0 ${pxTransform(pageMargin)}` }}>
                <View className='goods-wrap__title'>{item.title}</View>
                <View className='goods-wrap__more d-f a-i-c' onClick={() => toAnyPage(item.moreUrl)}>
                  {item.moreName}
                  <View className='bnn-icon'>&#xe866;</View>
                </View>
              </View>}
              <View className='goods-wrap__body'>
                <GoodsTen {...item} marginTop={pageMargin} />
              </View>
            </View>}

            {/* 商品列表模板1 */}
            {item.key === 'goodsList' && [2, 3, 4, 5, 6, 7].indexOf(Number(item.showMod)) >= 0 && <View className='goods-wrap goods-wrap__one' style={{ marginTop: pxTransform(marginTop) }}>
              {item.title && <View className='goods-wrap__head d-f a-i-b j-c-b' style={{ padding: `0 ${pxTransform(pageMargin)}` }}>
                <View className='goods-wrap__title'>{item.title}</View>
                <View className='goods-wrap__more d-f a-i-c' onClick={() => toAnyPage(item.moreUrl)}>
                  {item.moreName}
                  <View className='bnn-icon'>&#xe866;</View>
                </View>
              </View>}
              {item.coverImg && <View className='goods-wrap__cover-img d-f' style={{ padding: `0 ${pxTransform(pageMargin)}`, marginTop: `${pxTransform(pageMargin)}` }}>
                <Image mode="widthFix" src={item.coverImg} style={{ width: '100%' }} onClick={() => toAnyPage(item.coverUrl)} />
              </View>}
              <View className='goods-wrap__body'>
                {
                  {
                    2: <GoodsTwo {...item} marginTop={pageMargin} />,
                    3: <GoodsThree {...item} marginTop={pageMargin} />,
                    4: <GoodsFour {...item} />,
                    5: <GoodsFive {...item} />,
                    6: <GoodsSix {...item} marginTop={pageMargin} />,
                    7: <GoodsSeven {...item} marginTop={pageMargin} />,
                  }[item.showMod]
                }
              </View>
            </View>}

            {/* 商品列表模板2 */}
            {item.key === 'goodsList' && [1].indexOf(Number(item.showMod)) >= 0 && <View className='goods-wrap goods-wrap__two' style={{ marginTop: pxTransform(marginTop) }}>
              {item.coverImg && <Image mode="widthFix" src={item.coverImg} className='goods-wrap__cover-img' style={{ width: '100%' }} onClick={() => toAnyPage(item.coverUrl)} />}
              <View className='goods-wrap__box' style={{ margin: `${pxTransform(item.imgMarginTop)} ${pxTransform(item.pageMargin)} 0 ${pxTransform(item.pageMargin)}` }}>
                {item.title && <View className='goods-wrap__head d-f a-i-b j-c-b'>
                  <View className='goods-wrap__title'>{item.title}</View>
                  <View className='goods-wrap__more d-f a-i-c' onClick={() => toAnyPage(item.moreUrl)}>
                    {item.moreName}
                    <View className='bnn-icon'>&#xe866;</View>
                  </View>
                </View>}
                <View className='goods-wrap__body'>
                  {/* 商品列表 */}
                  {item.showMod === 1 && <GoodsOne {...item} />}
                </View>
              </View>
            </View>}
          </View>)
        })}
        <Version />
      </View>

      <View className='index-category' style={{ display: tabKey !== defTabKey ? 'block' : 'none' }}>
        <GoodsTwo id={`goods-list`} list={goodsList} pageMargin={30} marginTop={30} />
        <LoadMore status={loadStatus} />
        {loadStatus === 'noMore' && <Version />}
      </View>
      <AtModal isOpened={showRule}>
        <AtModalHeader>活动规则</AtModalHeader>
        <AtModalContent>
          <View className="rule_modal">
            <Text className="rule_content">1. 如何获取兑换币：每个新用户可领取7185体验兑换币，还可通过签到和购买返兑换币商品获取兑换币；</Text >
            <Text className="rule_content">2. 新用户是指没有在本商城提交过订单的用户，同一账号、同一手机号、同一终端设备号或其它合理显示为同一用户的情形，均视为同一用户；</Text >
            <Text className="rule_content">3. 参与商品：限兑换币兑换活动页面内的所有商品；</Text >
            <Text className="rule_content">4. 兑换币可以在下单时兑换商品或抵扣现金，具体使用标准请参考兑换币使用说明；</Text >
            <Text className="rule_content">5. 兑换币是有有效期的，体验兑换币为获取后的7天内有效；</Text >
            <Text className="rule_content">6. 非质量问题不给予退换，兑换币已兑换商品退换需联系客服；</Text >
            <Text className="rule_content">7. 如遇不可抗力因素，商城有权取消、修改或暂停本活动。如发现用户以不正当手段参与本次活动，商城有权取消其扣除兑换币，并要求其对已发放的活动所得进行返还；</Text >
            <Text className="rule_content">8. 在法律允许范围内，商城对此活动拥有最终解释权。未尽事宜请咨询客服</Text >
          </View>
        </AtModalContent>
        <AtModalAction> <Button onClick={this.toExchangeRule.bind(this, false)} className="rule_btn">我知道了</Button> </AtModalAction>
      </AtModal>

      {/*<ActivityGoods isOpened={showActivity} info={activityInfo} onClose={this.closeActivity.bind(this)}/>*/}
      {/*<ActivityCoupon isOpened={showActivity} info={activityInfo} onClose={this.closeActivity.bind(this)}/>*/}

      {/*<BuyRecord top={82} infinite/>*/}
      {/* {scoreInfo.totalScore > 0 && <HomePrompt top={0} score={scoreInfo.totalScore} />} */}



      {!loading && <CustomerService isOpened />}

      <View style={{ height: `${TAB_BAR_HEIGHT}px` }} />
      <TabBar />
    </View>)
  }
}
